import os
import traceback
from flask import Blueprint, request, jsonify, current_app
from openai import OpenAI

# Blueprint 注册，URL 前缀 /api/ai
ai_controller = Blueprint('ai_controller', __name__, url_prefix='/api/ai')

# 从环境变量读取 Deepseek/OpenAI API Key
DEESEEK_API_KEY = 'sk-039b9150ab7245868bff61138eb0a7dc'
if not DEESEEK_API_KEY:
    current_app = None  # 防止导入时报错；确保在 app context 中设置环境变量

# 初始化 OpenAI 客户端，指向 Deepseek 的 Base URL
openai_client = OpenAI(
    api_key=DEESEEK_API_KEY,
    base_url="https://api.deepseek.com"
)

@ai_controller.route('/chat', methods=['POST'])
def chat():
    """
    POST /api/ai/chat
    请求 JSON: { message: string, context: object }
    返回 JSON: { code: 0, reply: string }
    """
    try:
        data = request.get_json(force=True)
        user_msg = data.get('message')
        context = data.get('context')  # 获取用户持仓风险信息

        if not user_msg:
            return jsonify({'code': 1, 'msg': '缺少 message 参数'}), 400

        # 构造上下文信息
        context_str = f"用户持仓风险信息: {context}" if context else "无持仓风险信息"
        current_app.logger.debug(f"Context String: {context_str}")  # 打印上下文信息
        
        # 构造 Deepseek-Chat 请求
        response = openai_client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "你是一个有帮助的金融投资 AI 助手。输出的时候不使用markdown格式。"},
                {"role": "system", "content": context_str},  # 添加上下文信息
                {"role": "user", "content": user_msg}
            ],
            stream=False
        )

        # 提取回复内容
        reply = response.choices[0].message.content
        current_app.logger.debug(f"AI Reply: {reply}")  # 打印 AI 的回复内容
        return jsonify({'code': 0, 'reply': reply}), 200

    except Exception as e:
        # 日志错误堆栈
        current_app.logger.error(f"[AI] Chat 调用失败: {e}")
        current_app.logger.error(traceback.format_exc())
        return jsonify({'code': 1, 'msg': 'AI 请求失败，请稍后再试'}), 500